package io.zhifei.modules.sys.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zhifei.common.exception.RRException;
import io.zhifei.common.utils.PageUtils;
import io.zhifei.common.utils.ToolUtils;
import io.zhifei.modules.sys.system.dao.SysDictDao;
import io.zhifei.modules.sys.system.entity.SysDictEntity;
import io.zhifei.modules.sys.system.form.SysDictParam;
import io.zhifei.modules.sys.system.form.SysDictResult;
import io.zhifei.modules.sys.system.service.SysDictService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author duke
 * @since 2020-11-09
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {


    @Override
    public void addDict(SysDictParam param) {
        if (StrUtil.isEmpty(param.getPid())){
            //通过code获取字典信息
            SysDictResult result = this.baseMapper.getDetail(param);
            param.setPid(result.getId());
        }
        SysDictEntity entity = getEntity(param);
        this.baseMapper.insert(entity);
    }

    @Override
    public void updateDict(SysDictParam param) {
        SysDictResult dictResult = this.baseMapper.getDetail(param);
        if (StrUtil.isNotEmpty(dictResult.getCode())){
            throw new RRException("该字典暂不能删除！");
        }
        SysDictEntity oldEntity = getOldEntity(param);
        SysDictEntity entity = getEntity(param);
        ToolUtils.copyProperties(entity,oldEntity);
        this.baseMapper.updateById(entity);
    }


    @Override
    public SysDictResult getDetail(SysDictParam param) {
        return this.baseMapper.getDetail(param);
    }

    @Override
    public PageUtils getPageList(Page page, SysDictParam param) {
        IPage dictPageList = this.baseMapper.getPageList(page,param);
        return new PageUtils(dictPageList);
    }

    @Override
    public List<SysDictResult> getList(SysDictParam param) {
        if (StrUtil.isNotEmpty(param.getSeaTypes())){
            param.setSeaTypeList(param.getSeaTypes().split(","));
        }
        List<SysDictResult> dictResults = this.baseMapper.getList(param);
        return dictResults;
    }

    @Override
    public List<SysDictResult> getTreeList(SysDictParam param) {
        return this.baseMapper.getTreeList(param);
    }

    /**
     * 转化对象
     * @param param 参数
     * @return
     */
    private SysDictEntity getEntity(SysDictParam param){
        SysDictEntity entity = new SysDictEntity();
        ToolUtils.copyProperties(param,entity);
        return entity;
    }

    /**
     * 获取旧的数据
     * @param param
     * @return
     */
    private SysDictEntity getOldEntity(SysDictParam param){
        return this.getById(param.getId());
    }
}
